// @flow
import React from 'react'
import R from 'ramda'
import { Form, Checkbox, Input, DatePicker, Select, Button, notification,
  Popconfirm, message, TreeSelect, Switch } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
import styles from './TaskAdd.css'

const FormItem = Form.Item
const Option = Select.Option
const CheckboxGroup = Checkbox.Group
import moment from 'moment'
import { connect } from 'react-redux'
const config = {
  rules: [{ type: 'object', required: true, message: '请选择日期' }]
}
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}
const options = [
  { label: '邮件通知', value: 'mail' },
  { label: '短信通知', value: 'sms' },
  { label: '站内通知', value: 'amq' }
]
const results = [
  { label: '预警', value: 'warning' },
  { label: '统计指标', value: 'statistical' },
  { label: '事件', value: 'event' },
  { label: '时序', value: 'sensor' },
  { label: '规则', value: 'rules' }
]

type Props = {
  userId: string,
  history: Object,
  form: Object
}

type State = {
  models: Array<Object>,
  deviceTypes: Array<Object>,
  deviceParts: Array<Object>,
  customers: Array<Object>,
  devices: Array<Object>,
  kmxShow: string,
  resultActions: string,
  visible: boolean,
  loading: boolean,
  varData: Array<Object>,
  varDataCalculate: Array<Object>,
  channel: Array<Object>,
  pointDataAll: Array<Object>,
  devicePointData: Array<Object>,
  devicePartValue: Array<Object>,
  taskType: string,
  numValue: string,
  maxValue: string,
  minValue: string,
  analysisParams: Array<any>,
  analysisParamName: string,
  devicePointCalculate: Array<any>,
  isAdministor: boolean,
  customerIdLocal: string
}

class TaskAdd extends React.Component {
  props: Props
  state: State
  submit: Function
  getDeviceTypes: Function
  getCustomers: Function
  getModels: Function
  getTemplatePointCalculate: Function
  changeCustomer: Function
  changeDeviceType: Function
  changeDevice: Function
  changeResult: Function
  changeisible: Function
  isNeedKmx: Function
  initChildren: Function
  changeChannel: Function
  disabledDate: Function
  setDisableDate: Function
  changeDevicePoint: Function
  changeDevicePointCalculate: Function
  onblureFre: Function
  changeNumValue: Function
  timeChange: Function
  getAnalysisParams: Function
  changeAnalysisParam: Function
  isAdministor: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      models: [],
      deviceTypes: [],
      deviceParts: [],
      devicePartValue: [],
      customers: [],
      devices: [],
      kmxShow: 'none',
      resultActions: 'block',
      visible: false,
      loading: false,
      varData: [],
      varDataCalculate: [],
      devicePointData: [],
      pointDataAll: [],
      channel: [{ value: 'all', label: '全部' }],
      taskType: 'auto',
      numValue: '30',
      maxValue: '59',
      minValue: '1',
      analysisParams: [],
      analysisParamName: '',
      devicePointCalculate: [],
      isAdministor: false,
      customerIdLocal: ''
    }
    this.submit = this.submit.bind(this)
    this.getDeviceTypes = this.getDeviceTypes.bind(this)
    this.isAdministor = this.isAdministor.bind(this)
    this.getCustomers = this.getCustomers.bind(this)
    this.getModels = this.getModels.bind(this)
    this.isNeedKmx = this.isNeedKmx.bind(this)
    this.changeDeviceType = this.changeDeviceType.bind(this)
    this.changeCustomer = this.changeCustomer.bind(this)
    this.changeResult = this.changeResult.bind(this)
    this.changeDevice = this.changeDevice.bind(this)
    this.changeDevicePoint = this.changeDevicePoint.bind(this)
    this.getTemplatePointCalculate = this.getTemplatePointCalculate.bind(this)
    this.changeDevicePointCalculate = this.changeDevicePointCalculate.bind(this)
    this.changeChannel = this.changeChannel.bind(this)
    this.getAnalysisParams = this.getAnalysisParams.bind(this)
    this.changeAnalysisParam = this.changeAnalysisParam.bind(this)
    this.onblureFre = this.onblureFre.bind(this)
    this.changeNumValue = this.changeNumValue.bind(this)
    this.timeChange = this.timeChange.bind(this)
    this.handleTaskType = this.handleTaskType.bind(this)
    this.changeisible = this.changeisible.bind(this)

    this.disabledDate = this.disabledDate.bind(this)
    this.setDisableDate = this.setDisableDate.bind(this)
    this.preDate = Date.now()
  }

  componentWillMount () {
    // 当前用户是否是管理员
    this.isAdministor()
    // 设备类型
    this.getDeviceTypes()
    // 获取客户
    this.getCustomers()
    // 获取模型
    this.getModels()
    // 模型参数
    this.getAnalysisParams()
    // 计算量测点
    this.getTemplatePointCalculate()
  }
  submit () {
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      const values = {
        ...fieldsValue,
        taskType: this.state.taskType
      }
      values.device.map((d, i) => {
        if (d['deviceId'] == null) {
          d['deviceId'] = d.key
        }
        if (d['deviceName'] == null) {
          d['deviceName'] = d.label
        }
        if (d['deviceNo'] == null) {
          d['deviceNo'] = d.title
        }
        return d
      })
      if (values.device.length === 1 && values.device[0].deviceId === 'all') {
        values.device = []
      }
      if (values.channel.value == null) {
        values.channel.value = values.channel.title
      }
      if (values.channel.key == null) {
        values.channel.key = values.channel.title
      }
      if (values.deviceType.key == null) {
        values.deviceType = values.deviceType.value
      } else {
        values.deviceType = values.deviceType.key
      }
      if (values.startDate !== null) {
        values.startDate = moment.utc(values.startDate, 'YYYY-MM-DDTHH:mm:ss.SSSZ')
      }
      if (values.endDate !== null) {
        values.endDate = moment(values.endDate)
      }
      if (values.customerId === 'all') {
        values.customerId = null
      }
      if (values.devicePoint != null) {
        values.devicePoint = null
      }
      values.varData.map((k, v) => {
        if (k.key.split('_').length === 3) {
          let finalKey = k.key.split('_')[0] + '_' + k.key.split('_')[1] + '_' +
          values.channel.key + '_' + k.key.split('_')[2]
          k.key = finalKey
        } else if (k.key.split('_').length === 4) {
          let finalKey = k.key.split('_')[0] + '_' + k.key.split('_')[1] + '_' +
          values.channel.key + '_' + k.key.split('_')[3]
          k.key = finalKey
        }
      })
      console.log(values)
      let params = JSON.stringify(values)
      universalFetch(`${__SERVICE_API__}analysis/tasks`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: params
        })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        if (json.code === 200000) {
          notification.open({
            message: '任务添加提醒',
            description: '任务添加成功'
          })
          this.props.history.push('/analysis/tasks')
        } else {
          notification.error({
            message: '提醒',
            description: json.message,
            duration: 7
          })
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
      })
      .catch((error) => {
        notification.error({
          message: '添加失败',
          description: error.message,
          duration: 7
        })
        handleFetchError(error)
        console.error(error)
      })
    })
  }

  isAdministor () {
    universalFetch(`${__SERVICE_API__}sys/users/${this.props.userId}/roles`)
    .then(res => {
      return res.json()
    })
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        if (json.result[0].enname === 'Administrator') {
          this.setState({ isAdministor: true })
        }
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  /**
  提交前检查是否同步
  **/
  changeisible () {
  }

  /**
    获取模型所需参数
  **/
  getAnalysisParams () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=analysisParams`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        if (json.result.analysisParams !== null) {
          this.setState({
            analysisParams: json.result.analysisParams
          })
        }
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  /**
  获取计算量测点
  **/
  getTemplatePointCalculate () {
    universalFetch(`${__SERVICE_API__}device/templates/monitors/points?nameEn=c_calculate`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        this.setState({
          devicePointCalculate:result.map((data, index) => {
            data['key'] = data.id
            data['value'] = data.id
            data['label'] = data.sensorName
            return data
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  changeAnalysisParam (value) {
    this.setState({ analysisParamName: value })
  }
  getDeviceTypes () {
    universalFetch(`${__SERVICE_API__}device/templates/devices?type=deep`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        this.setState({
          deviceTypes:result.map((data, index) => {
            data['key'] = index
            data['value'] = data.id
            data['label'] = data.name
            return data
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getCustomers () {
    universalFetch(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageNum=1&pageSize=1000`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        let customers = []
        if (this.state.isAdministor) {
          customers = [{ id: 'all', name: '全部' }]
        }
        let results = result.map((data, index) => {
          data['key'] = index
          return data
        })
        customers.push(...results)
        this.setState({
          customers: customers
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getModels () {
    universalFetch(`${__SERVICE_API__}analysis/models/simple`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        this.setState({
          models:result.map((data, index) => {
            data['key'] = index
            data['name'] = data['projName']
            return data
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  isNeedKmx () {
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      const values = {
        ...fieldsValue
      }
      const fieldGroupId = values.channel.title
      if (fieldGroupId == null || fieldGroupId === undefined) {
        message.success('测点没有关联fieldGroup')
        return false
      }
      universalFetch(`${__SERVICE_API__}analysis/templates/fieldGroup/status?fieldGroup=` + fieldGroupId,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json;charset=utf-8'
          }
        })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        if (result) {
          this.submit()
        } else {
          // 尚未同步
          console.log('尚未同步,弹出提示!')
          this.setState({ visible: true })
        }
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        return false
      })
    })
  }

  cancel = () => {
    this.setState({ visible: false })
  }
  confirmKmx = () => {
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      const values = {
        ...fieldsValue
      }
      const fieldGroupId = values.channel.title
      if (fieldGroupId) {
        this.setState({
          loading: true
        })
        universalFetch(`${__SERVICE_API__}device/kmx/meta2kmx?pointId=${values.deviceType.key}`)
          .then(res => res.json())
          .then((json) => {
            if (json.code !== 200000) {
              throw new Error(JSON.stringify({ code: json.code, message: json.message }))
            }
            this.setState({
              loading: false
            })
            this.cancel()
            message.success('同步选中设置成功')
          })
          .catch((error) => {
            handleFetchError(error)
            console.error(error)
            this.setState({
              loading: false
            })
            message.error('同步选中设置失败: ' + err.message)
          })
      } else {
        this.setState({
          loading: false
        })
        message.info('此数据不能同步')
      }
    })
  }
  /**
  失效时间
  **/
  disabledDate (current) {
    return current && current.valueOf() < this.preDate
  }
  /**
  生效时间
  **/
  setDisableDate (val) {
    this.preDate = val > Date.now() ? val : Date.now()
  }
    /**
    * 自动手动切换
    **/
  handleTaskType () {
    let taskType = this.state.taskType === 'auto' ? 'manual' : 'auto'
    this.setState({ taskType })
  }
    /**
    启动频率
    **/
  changeNumValue (e) {
    const { value } = e.target
    const reg = /^-?(0|[1-9][0-9]*)([0-9]*)?$/
    if ((!isNaN(value) && reg.test(value)) || value === '') {
      this.setState({
        numValue: value
      })
    }
  }
  onblureFre (e) {
    const { value } = e.target
    const { maxValue, minValue } = this.state
    if (Number(value) > Number(maxValue)) {
      this.setState({
        numValue: maxValue
      })
    }
    if (value === '0') {
      this.setState({
        numValue: minValue
      })
    }
  }
  /**
  时间单位改变
  **/
  timeChange (value) {
    if (value === 'minute') {
      this.setState({
        maxValue: '59'
      })
    }
    if (value === 'hour') {
      this.setState({
        maxValue: '23'
      })
    }
  }
  /**
  * 改变设备类型
  **/
  changeDeviceType (value) {
    this.state.deviceTypes.map((data, index) => {
      if (data.id === value.key) {
        this.setState({
          deviceParts: data.children.map((data, index) => {
            let data1 = {}
            data1['key'] = '0' + '-' + index + ''
            data1['value'] = data.id
            data1['label'] = data.name
            data1['children'] = data.children
            this.initChildren(data1)
            return data1
          })
        })
      }
    })
  }
  initChildren (object) {
    const children = object.children.map((data, index) => {
      let data1 = {}
      data1['key'] = object.key + '-' + index + ''
      data1['value'] = data.id + ''
      data1['label'] = data.name + ''
      data1['children'] = data.children
      this.initChildren(data1)
      return data1
    })
    object['children'] = children
  }
  /**
  改变设备部件
  **/
  onChange = (value) => {
    this.setState({ devicePartValue: value })
  }
  /**
  改变客户
  **/
  changeCustomer (value) {
    if (value === 'all') {
      let devices = [{ key:'all', value:'all', label:'全部' }]
      this.setState({
        devices:devices,
        customerIdLocal: 'all'
      })
    } else {
      universalFetch(`${__SERVICE_API__}device/customers/${value}/devices`)
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          const result = json.result
          let device = [{ key:'all', value:'all', label:'全部' }]
          let devices = result.map((data, index) => {
            data['key'] = data.id
            data['value'] = data.deviceNo
            data['label'] = data.name
            return data
          })
          device.push(...devices)
          this.setState({
            devices: device,
            customerIdLocal: value
          })
          this.props.form.resetFields(['device'])
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
        })
    }
  }
  /**
  * 设备改变事件
  **/
  changeDevice (value) {
    var device0 = {}
    if (value.length === 0) {
      return
    }
    device0 = value[0]
    let url = `${__SERVICE_API__}device/templates/monitors/points`
    if (device0.key === 'all') {
      if (this.state.customerIdLocal === 'all') {
        url = `${__SERVICE_API__}device/templates/monitors/points`
      } else {
        url = `${__SERVICE_API__}device/templates/monitors/points?customerId=${this.state.customerIdLocal}`
      }
    } else {
      url = `${__SERVICE_API__}device/templates/monitors/points?customerId=${this.state.customerIdLocal}&deviceId=${device0.key}`
    }
    universalFetch(url)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        pointDataAll:json.result.map((k, i) => {
          var d = {}
          d['sensorName'] = k.sensorName
          d['tMonitorPointId'] = k.id
          d['mointorPointId'] = k.id
          d['deviceId'] = 'all'
          d['children'] = []
          return d
        })
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  /**
  改变测点
  **/
  changeDevicePoint (value) {
    const pointsThis = this.state.pointDataAll.filter((dd) => dd.sensorName === value.label)
    let tMonitorPointId = ''
    let deviceId = ''
    let mointorPointId = ''
    if (pointsThis.length > 0) {
      tMonitorPointId = pointsThis[0].tMonitorPointId || ''
      deviceId = pointsThis[0].deviceId || ''
      mointorPointId = pointsThis[0].mointorPointId || ''

      let channels = [{ value: 'all', label: '全部' }]
      let channel = pointsThis[0].children.map((data, index) => {
        var d = {}
        d['key'] = data.channelId
        d['value'] = data.nameEn
        d['label'] = data.channelName
        d['sensorName'] = data.sensorName
        return d
      })
      channels.push(...channel)
      this.setState({
        channel: channels
      })
    }
    const url =
    `${__SERVICE_API__}device/templates/monitors/variables?monitorPointId=${tMonitorPointId}`
    universalFetch(url)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          varData: json.result.map((data, index) => {
            const data1 = {}
            data1['key'] = deviceId + '_' + mointorPointId + '_' + data.id
            data1['value'] = data.variableType + ',' + data.variableNameEn
            data1['label'] = data.variableName
            return data1
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  /**
  改变计算量测点
  **/
  changeDevicePointCalculate (value) {
    universalFetch(`${__SERVICE_API__}device/templates/monitors/variables?monitorPointId=${value.key}`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        varDataCalculate: json.result.map((data, index) => {
          const data1 = {}
          data1['key'] = value.key + '_' + data.id
          data1['value'] = data.variableType + ',' + data.variableNameEn
          data1['label'] = data.variableName
          return data1
        })
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  /**
  改变通道
  **/
  changeChannel (value) {
    var values = value.key.split('_')
    const deviceId = values[0]
    const monitorPointId = values[1]
    const url =
    `${__SERVICE_API__}device/devices/monitors/variables?deviceId=${deviceId}&monitorPointId=${monitorPointId}`
    universalFetch(url)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          varData: json.result.map((data, index) => {
            const data1 = {}
            data1['key'] = value.key + '_' + data.id
            data1['value'] = data.variableType + ',' + data.variableNameEn
            data1['label'] = data.variableName
            return data1
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  /**
  改变输出结果
  **/
  changeResult (value) {
    let kmxShow = 'none'
    let resultActions = 'block'
    if (value === 'event' || value === 'warning') {
      kmxShow = 'none'
      resultActions = 'block'
    } else if (value === 'statistical') {
      kmxShow = 'block'
      resultActions = 'none'
    } else {
      kmxShow = 'none'
      resultActions = 'none'
    }
    this.setState({
      kmxShow: kmxShow,
      resultActions: resultActions
    })
  }
  render () {
    const { loading, taskType, deviceParts, numValue, analysisParams } = this.state
    const { getFieldDecorator } = this.props.form
    const { history } = this.props
    const { state } = history.location
    let modelFieldDecorator
    let frequencyFlag = taskType === 'manual'
    if (state && state.modelId) {
      modelFieldDecorator = getFieldDecorator('modelId', {
        rules: [{ required: true, message: '请选择模型' }],
        initialValue: `${state.modelId}`
      })
    } else {
      modelFieldDecorator = getFieldDecorator('modelId', {
        rules: [{ required: true, message: '请选择模型' }]
      })
    }
    // 设备部件
    const tProps = {
      treeData: deviceParts,
      value: this.state.devicePartValue,
      onChange: this.onChange,
      multiple: false,
      treeCheckable: false,
      treeDefaultExpandAll: true,
      showCheckedStrategy: SHOW_PARENT,
      placeholder: '请选择设备部件',
      searchPlaceholder: 'Please select',
      style: {
        width: 300
      }
    }
    const prefixSelector = getFieldDecorator('prefix', {
      initialValue: '分钟'
     })(
       <Select style={{ width: 60 }} onChange={this.timeChange}>
         <Option value='minute'>分钟</Option>
         <Option value='hour'>小时</Option>
         <Option value='day'>天</Option>
         <Option value='month'>月</Option>
       </Select>
     )
    //  启动频率
    let label =  <FormItem
      {...formItemLayout}
      label='启动频率'
      hasFeedback
    >
      {getFieldDecorator('frequency', {
        rules: [{ required: true, message: '请输入启动频率', whitespace: true }],
        initialValue: '30'
      })(
        <div>
          <Input addonAfter={prefixSelector} placeholder='请输入启动频率' disabled={frequencyFlag}
            className={styles['ant-input']} style={{ width: 150 }}
            value={numValue}
            onBlur={this.onblureFre}
            onChange={this.changeNumValue} />
        </div>
      )}
    </FormItem>

    if (frequencyFlag) label = ''

    const channel = {}
    channel['key'] = 'all'
    channel['value'] = 'all'
    channel['label'] = '全部'
    channel['sensorName'] = '全部'
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.submit}>
          <FormItem
            {...formItemLayout}
            label='任务名称'
            hasFeedback
          >
            {getFieldDecorator('taskName', {
              rules: [{ required: true, message: '请输入任务名称', whitespace: true }],
              initialValue: '任务1'
            })(
              <Input placeholder='请输入任务名称' />
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label='模型'
          >
            {modelFieldDecorator(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择模型'>
                {
                  this.state.models.map((d, i) => {
                    return <Option value={`${d.id}`}>{d.name}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='生效时间'
            hasFeedback
          >
            {getFieldDecorator('startDate', config)(
              <DatePicker showTime format='YYYY-MM-DD HH:mm:ss' style={{ width: '70%' }}
                onChange={this.setDisableDate} />
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label='失效时间'
            hasFeedback
            >
            {getFieldDecorator('endDate', config)(
              <DatePicker showTime format='YYYY-MM-DD HH:mm:ss' style={{ width: '70%' }}
                disabledDate={this.disabledDate} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='任务类型' hasFeedback>
            <Switch checkedChildren='自动' unCheckedChildren='手动' onChange={this.handleTaskType} defaultChecked />
          </FormItem>
          {label}
          <FormItem
            {...formItemLayout}
            label='任务描述'
            hasFeedback
          >
            {getFieldDecorator('details', {
              rules: [{ required: false, message: '请输入任务描述' }]
            })(
              <Input placeholder='请输入任务描述' />
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label='设备类型'
          >
            {getFieldDecorator('deviceType', {
              rules: [{ required: true, message: '请选择设备类型' }]
            })(
              <Select showSearch labelInValue
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择设备类型'
                onChange={this.changeDeviceType}>
                {
                  this.state.deviceTypes.map((d, i) => {
                    return <Option title={d.fieldGroupId} value={d.value}>{d.label}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label='设备部件'
            hasFeedback
          >
            {getFieldDecorator('deviceParts', {
              rules: [{ required: false, message: '请选择设备部件' }]
            })(
              <TreeSelect {...tProps} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='客户信息'
          >
            {getFieldDecorator('customerId', {
              rules: [{ required: true, message: '请选择客户' }]
            })(
              <Select
                showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择客户'
                onChange={this.changeCustomer}>
                {
                  this.state.customers.map((d, i) => {
                    return <Option value={`${d.id}`}>{d.name}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label='设备编号'
          >
            {getFieldDecorator('device', {
              rules: [{ required: true, message: '请选择设备编号' }]
            })(
              <Select multiple labelInValue allowClear showSearch
                onChange={this.changeDevice}
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择设备编号'>
                {
                  this.state.devices.map((d, i) => {
                    return <Option title={d.value} value={d.key}>{d.label}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='测点'
          >
            {getFieldDecorator('devicePoint', {
              rules: [{ required: true, message: '请选择测点' }]
            })(
              <Select
                showSearch labelInValue
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择测点'
                onChange={this.changeDevicePoint}>
                {
                  this.state.pointDataAll.map((d, i) => {
                    return <Option key={i} value={d.mointorPointId}>{d.sensorName}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='测点变量'
          >
            {getFieldDecorator('varData', {
              rules: [{ required: true, message: '请选择测点变量' }]
            })(
              <Select multiple labelInValue allowClear showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择测点变量'>
                {
                  this.state.varData.map((d, i) => {
                    return <Option value={d.key}>{d.label}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='通道'
          >
            {getFieldDecorator('channel', {
              rules: [{ required: true, message: '请选择通道' }],
              initialValue: channel
            })(
              <Select
                showSearch labelInValue
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择通道'>
                {
                  this.state.channel.map((d, i) => {
                    return <Option title={d.value} value={d.key}>{d.label}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='输出结果'
          >
            {getFieldDecorator('result', {
              rules: [{ required: true, message: '请选择输出结果' }],
              initialValue: 'warning'
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择输出结果'
                onChange={this.changeResult}>
                {
                   results.map((d, i) => {
                     return <Option value={d.value}>{d.label}</Option>
                   })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='模型参数'
            style={{ display:this.state.kmxShow }}
            hasFeedback
          >
            {getFieldDecorator('analysisParamName', {
              rules: [{ required: false, message: '', whitespace: true }]
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择'
                onChange={this.changeAnalysisParam}>
                {
                  analysisParams.map((item, i) => {
                    return <Option key={i} value={item.value}>
                      {item.label}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='模型参数值'
            style={{ display:this.state.kmxShow }}
            hasFeedback
          >
            {getFieldDecorator('analysisParamValue', {
              rules: [{ required: false, message: '', whitespace: true }]
            })(
              <Input placeholder='' />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='结果通知'
            style={{ display:this.state.resultActions }}
          >
            {getFieldDecorator('actions', {
              rules: [{ required: true, message: '请选择结果通知' }],
              initialValue: ['amq']
            })(
              <CheckboxGroup options={options} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='计算结果保存到'
            style={{ display:this.state.kmxShow }}
           >
            {getFieldDecorator('pointData10', {})(
              <span className='ant-form-text'></span>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='测点'
            style={{ display:this.state.kmxShow }}
          >
            {getFieldDecorator('devicePointCalculate', {
              rules: [{ required: false, message: '请选择测点' }]
            })(
              <Select
                showSearch labelInValue
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择测点'
                onChange={this.changeDevicePointCalculate}>
                {
                  this.state.devicePointCalculate.map((d, i) => {
                    return <Option value={d.key}>{d.label}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='测点变量'
            style={{ display:this.state.kmxShow }}
          >
            {getFieldDecorator('varDataCalculate', {
              rules: [{ required: false, message: '请选择测点变量' }]
            })(
              <Select labelInValue allowClear showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择测点变量'>
                {
                  this.state.varDataCalculate.map((d, i) => {
                    return <Option value={d.key}>{d.label}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...tailFormItemLayout}
            className={styles['goBackBtn']}
          >
            <Popconfirm
              title='设备类型还未同步到kmx,是否同步?'
              loading={loading}
              visible={this.state.visible}
              onVisibleChange={this.changeisible}
              onConfirm={this.confirmKmx}
              onCancel={this.cancel}
              okText='Yes'
              cancelText='No'
            >
              <Button type='primary'
                htmlType='button'
                className='login-form-button'
                onClick={this.submit}>
                提交
              </Button>
            </Popconfirm>
            <Button style={{ marginLeft: '20px', height: '28px', fontSize: '12px' }}
              onClick={() => { this.props.history.push('/analysis/tasks') }}
              >
              返回
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(TaskAdd))
